package com.yzg.simple.netty.unpacking.unpacking_solve.client;

import com.yzg.simple.netty.unpacking.unpacking_solve.codec.MessageDecode;
import com.yzg.simple.netty.unpacking.unpacking_solve.codec.MessageEncode;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author misterWei
 * @create 2019年12月26号:23点08分
 * @mailbox mynameisweiyan@gmail.com
 *
 * 基于解决Netty TCP 粘包拆包 示例代码
 *
 *
 */
public class NettyTcpClient {

    public static void main(String[] args)throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(group)
                    //和服务端不同客户端是NioSocketChannel
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                           //加入自定义的 编码处理器
                            pipeline.addLast(new MessageEncode());
                            //添加自定义的 解码器
                            pipeline.addLast(new MessageDecode());
                            pipeline.addLast(new ClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }

    }
}
